package com.yunshu.yunshuapp.xianhuo;

import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yunshu.yunshuapp.NavigationBar;
import com.yunshu.yunshuapp.R;
import com.yunshu.yunshuapp.network.YSCallback;
import com.yunshu.yunshuapp.network.YSRequest;
import com.yunshu.yunshuapp.user.YSUser;
import com.yunshu.yunshuapp.views.CommonLoadingView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

public class MyPostsActivity extends AppCompatActivity {

    private static final int MSG_RECYLEVIEW_UPDATE = 100;

    private YSRequest request;
    private Handler mExtHandler;
    private RecyclerView mRecyclerView;
    private ArrayList<Xianhuo> models;
    protected XianhuoListAdapter adapter;
    private SwipeRefreshLayout swipeRefreshLayout;
    protected CommonLoadingView loadingView;

    private int pageIndex = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_posts);

        NavigationBar bar = (NavigationBar) findViewById(R.id.navigationBar);
        bar.setTitle("我的发布");
        bar.putInActivity(this);

        request = new YSRequest(this);
        this.addList();
        this.initLoadMoreListener();
        mExtHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case MSG_RECYLEVIEW_UPDATE:
                        adapter.setModels(models);
                        adapter.notifyDataSetChanged();
                        break;
                }
                super.handleMessage(msg);
            }
        };
        loadingView = (CommonLoadingView) findViewById(R.id.loadingView);

        this.refresh();

    }

    private void addList() {
        mRecyclerView = (RecyclerView) findViewById(R.id.list_view);
        // use a linear layout manager
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        //设置RecycleView的显示方向：（默认为垂直） 水平
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setHasFixedSize(true);

        adapter = new XianhuoListAdapter(getBaseContext());
        adapter.activity = this;
        adapter.shouldShowAudit = true;
        mRecyclerView.setAdapter(adapter);

        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
        //设置刷新时动画的颜色，可以设置4个
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {
                refresh();
            }
        });
    }

    private void initLoadMoreListener() {

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            int lastVisibleItem ;
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                //判断RecyclerView的状态 是空闲时，同时，是最后一个可见的ITEM时才加载
                if(newState==RecyclerView.SCROLL_STATE_IDLE&&lastVisibleItem+1==adapter.getItemCount()){

                    loadmore();

                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                //最后一个可见的ITEM
                lastVisibleItem=layoutManager.findLastVisibleItemPosition();
            }
        });

    }
    private void loadmore() {
        if (!request.getIsCompleted())return;
        request.GET(this.getURL(), "page="+pageIndex+"&userid="+YSUser.instance().getUid(), new YSCallback() {

            @Override
            public void onResponse(int isSuccess, JsonNode result) {
                endRefreshing();
                if (isSuccess != YSRequest.REQUEST_OK) return;
                if (!result.isArray()) return;
                Iterator<JsonNode> iterator = result.iterator();
                ArrayList<Xianhuo> temp = new ArrayList<Xianhuo>();
                ObjectMapper mapper = new ObjectMapper();
                while (iterator.hasNext()){
                    String jsonstr = iterator.next().toString();
                    try {
                        Xianhuo model = mapper.readValue(jsonstr, Xianhuo.class);
                        temp.add(model);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                pageIndex +=1;
                models.addAll( temp);
                reloadData();
            }
        });
    }

    protected void refresh() {
        if (!request.getIsCompleted())return;
        loadingView.setVisibility(View.VISIBLE);
        loadingView.load();
        pageIndex = 1;
        request.GET(this.getURL(), "page=1"+"&userid="+YSUser.instance().getUid(), new YSCallback() {

            @Override
            public void onResponse(int isSuccess, JsonNode result) {
                endRefreshing();

                if (isSuccess != YSRequest.REQUEST_OK){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            loadingView.setVisibility(View.INVISIBLE);
                        }
                    });
                    return;
                }
                if (!result.isArray()){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            loadingView.setVisibility(View.INVISIBLE);
                        }
                    });
                    return;
                }
                Iterator<JsonNode> iterator = result.iterator();
                ArrayList<Xianhuo> temp = new ArrayList<Xianhuo>();
                ObjectMapper mapper = new ObjectMapper();
                while (iterator.hasNext()){
                    String jsonstr = iterator.next().toString();
                    try {
                        Xianhuo model = mapper.readValue(jsonstr, Xianhuo.class);
                        temp.add(model);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (temp.isEmpty()){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            loadingView.loadSuccess(true);
                        }
                    });
                }else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            loadingView.setVisibility(View.INVISIBLE);
                            loadingView.loadSuccess();                        }
                    });
                }
                models = temp;
                pageIndex +=1;
                reloadData();
            }
        });
    }

    private void reloadData() {

        Message msg;
        msg = Message.obtain();
        msg.what = MSG_RECYLEVIEW_UPDATE;
        mExtHandler.sendMessage(msg);

    }

    private void endRefreshing() {
        runOnUiThread(new Runnable() {      // UI thread
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(false);
            }
        });


    }

    public String getURL() {
        return YSRequest.XIANHUO_MINE_LIST;
    }
}
